<template>
  <template v-if="props.formStatus">
    <el-form-item :label="props.formStatus.payload.label">
      <el-input v-if="props.formStatus.type==='input'" v-model="props.formStatus.payload.value" />
      <el-select v-if="props.formStatus.type==='select'" v-model="props.formStatus.payload.value">
        <el-option
          v-for="item in props.formStatus.payload.options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-checkbox-group v-if="props.formStatus.type==='checkbox'" v-model="props.formStatus.payload.value">
        <el-checkbox
          v-for="item in props.formStatus.payload.options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-checkbox-group>
    </el-form-item>
    <form-item :form-status="getNext()" :form-state="props.formState"></form-item>
  </template>
</template>

<script setup lang="ts">
import { watchEffect } from 'vue';
import { IFormItem } from './FormItem';
import { ElFormItem, ElSelect, ElInput, ElCheckboxGroup, ElCheckbox } from 'element-plus';
const props = defineProps<{
  formStatus: IFormItem | null;
  formState?: any;
}>();

// 组件内getNext即为运行时，此时可以提供“正确”的current与acients
const getNext = () => {
  const current = props.formStatus;
  if(!current) return null;

  let ptr = current;
  const acients: IFormItem[]  = [];
  while(ptr && ptr.parent) {
    // 指针移动
    ptr = ptr.parent;
    // 浅拷贝 & 插入acients
    const acient = ptr;
    acients.unshift(acient);
  }

  return props.formStatus?.next(current, acients);
}

// 实现数据收集: 同步更新formState(formStatus.payload.value映射到formState[formStatus.payload.prop])
watchEffect(() => {
  const key = props.formStatus?.payload.prop;
  const value = props.formStatus?.payload.value;
  props.formState[key] = value;
})
</script>